package activity.helloWorld;

import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.SimpleFormatter;

/**
 * @Author: 蔡翔
 * @Date: 2019/8/17 19:06
 * @Version 1.0
 */
public class Demo {
    private static final Logger LOGGER = LoggerFactory.getLogger(Demo.class);
    public static void main(String[] args) throws ParseException {
        LOGGER.info("启动我们的程序");
        //创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String name = processEngine.getName();
        String version = ProcessEngine.VERSION;
        LOGGER.info("流程引擎名称[{}]，版本[{}]",name,version);

        //部署流程定义文件
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addClasspathResource("second_approve.bpmn");
        Deployment deployment = deploymentBuilder.deploy();
        String deploymentId = deployment.getId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        LOGGER.info("流程定义文件:[{}]，流程ID:[{}]",processDefinition.getName(),processDefinition.getId());
        //启动运行流程
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        LOGGER.info("启动流程 [{}]",processInstance.getProcessDefinitionKey());
        //处理流程任务
        Scanner scanner = new Scanner(System.in);
        while (processInstance != null && !processInstance.isEnded()){
            TaskService taskService = processEngine.getTaskService();
            List<Task> list = taskService.createTaskQuery().list();
            LOGGER.info("待处理任务数量[{}]",list.size());
            for(Task task : list){
                LOGGER.info("待处理任务[{}]",task.getName());
                FormService formService = processEngine.getFormService();
                TaskFormData taskFormData = formService.getTaskFormData(task.getId());
                List<FormProperty> formProperties = taskFormData.getFormProperties();
                Map<String,Object> variables = Maps.newHashMap();
                for(FormProperty property:formProperties){
                    String line = null;
                    if(StringFormType.class.isInstance(property.getType())){
                        LOGGER.info("请输入 {} ？",property.getName()); //这里的property.getName() 是bpmn表里面生成的。
                        line = scanner.nextLine();
                        variables.put(property.getId(),line);
                    }else if(DateFormType.class.isInstance(property.getType())){
                        LOGGER.info("您输入[{}]?格式 （yyyy-MM-dd）",property.getName());
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        line = scanner.nextLine();
                        Date date = dateFormat.parse(line);
                        variables.put(property.getId(),date);
                    }else {
                        LOGGER.info("类型暂不支持",property.getType());
                    }
                    LOGGER.info("您输入的内容是[{}]",line);
                }
                taskService.complete(task.getId(),variables);
                // 靠实例Id 新建一个实例的查询对象，并且只查询出一个实例，把这个实例赋值给 processInstance
                processInstance = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();

            }
        }
        scanner.close();  //注意scanner要记得关闭
        LOGGER.info("结束我们的程序");

    }
}
